import { SM2, SM4 } from 'gm-crypto';

export class MessageCrypto {
  constructor() {
    this.sm4Key = null;
    this.serverPublicKey = null;
    this.keyPair = null;
  }

  // 初始化SM2密钥对
  initKeyPair() {
    const keyPair = SM2.generateKeyPair();
    this.keyPair = keyPair;
    return keyPair.publicKey;
  }

  // 设置服务器公钥
  setServerPublicKey(publicKey) {
    this.serverPublicKey = publicKey;
  }

  // 生成并加密SM4密钥
  generateAndEncryptSM4Key() {
    this.sm4Key = this.generateRandomHex(32);
    
    return SM2.encrypt(this.sm4Key, this.serverPublicKey, {
      inputEncoding: 'utf8',
      outputEncoding: 'base64'
    });
  }

  // 解密服务器发送的SM4密钥
  decryptSM4Key(encryptedKey) {
    this.sm4Key = SM2.decrypt(encryptedKey, this.keyPair.privateKey, {
      inputEncoding: 'base64',
      outputEncoding: 'utf8'
    });
    return this.sm4Key;
  }

  // 加密消息
  encryptMessage(message) {
    if (!this.sm4Key) {
      throw new Error('SM4密钥未设置');
    }
    
    const messageStr = JSON.stringify(message);
    
    return SM4.encrypt(messageStr, this.sm4Key, {
      inputEncoding: 'utf8',
      outputEncoding: 'base64'
    });
  }

  // 解密消息
  decryptMessage(encryptedMessage) {
    if (!this.sm4Key) {
      throw new Error('SM4密钥未设置');
    }
    
    const decryptedStr = SM4.decrypt(encryptedMessage, this.sm4Key, {
      inputEncoding: 'base64',
      outputEncoding: 'utf8'
    });
    
    return JSON.parse(decryptedStr);
  }
  
  // 生成指定长度的随机十六进制字符串
  generateRandomHex(length) {
    const hexChars = '0123456789abcdef';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
    }
    return result;
  }
}